package com.meter.basic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meter.basic.domain.BasicDevice;
import com.meter.basic.domain.BasicMeter;
import com.meter.basic.mapper.BasicDeviceMapper;
import com.meter.basic.mapper.BasicMeterMapper;
import com.meter.basic.service.IBasicDeviceService;
import com.meter.common.constant.Constants;
import com.meter.common.constant.UserConstants;
import com.meter.common.core.text.Convert;
import com.meter.common.exception.ServiceException;
import com.meter.common.utils.DateUtils;
import com.meter.common.utils.StringUtils;
import com.meter.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class BasicDeviceServiceImpl extends ServiceImpl<BasicDeviceMapper, BasicDevice> implements IBasicDeviceService {

    @Autowired
    private RedisService redisService;

    @Autowired
    private BasicMeterMapper basicMeterMapper;

    public BasicDevice selectBasicDeviceById(Long deviceId) {
        return baseMapper.selectBasicDeviceById(deviceId);
    }

    public List<BasicDevice> selectBasicDeviceList(BasicDevice basicDevice) {
        List<BasicDevice> deviceList = baseMapper.selectBasicDeviceList(basicDevice);
        for (BasicDevice device : deviceList) {
            if (redisService.hHasKey("sys-netty", device.getDeviceCode())) {
                device.setOnlineStatus("online");
            } else {
                device.setOnlineStatus("offline");
            }
            if(redisService.hHasKey("online-time", device.getDeviceCode())) {
                device.setOnlineTime(redisService.hget("online-time", device.getDeviceCode()));
            }
            if(redisService.hHasKey("offline-time", device.getDeviceCode())) {
                device.setOfflineTime(redisService.hget("offline-time", device.getDeviceCode()));
            }
            long meterCount = basicMeterMapper.selectCount(Wrappers.lambdaQuery(BasicMeter.class).eq(BasicMeter::getDeviceId, device.getDeviceId()));
            device.setMeterCount(meterCount);
        }
        return deviceList;
    }

    public int insertBasicDevice(BasicDevice basicDevice) {
        basicDevice.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(basicDevice);
    }

    public int updateBasicDevice(BasicDevice basicDevice) {
        basicDevice.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(basicDevice);
    }

    public int deleteBasicDeviceByIds(String ids) {
        return baseMapper.deleteBatchIds(Arrays.asList(Convert.toLongArray(ids)));
    }

    public int deleteBasicDeviceById(Long deviceId) {
        return baseMapper.deleteById(deviceId);
    }

    /**
     * 校验sim卡号是否唯一
     *
     * @param basicDevice 用户信息
     * @return 结果
     */
    @Override
    public boolean checkDeviceCodeUnique(BasicDevice basicDevice){
        Long deviceId = StringUtils.isNull(basicDevice.getDeviceId()) ? -1L : basicDevice.getDeviceId();
        BasicDevice info = baseMapper.selectOne(new LambdaQueryWrapper<BasicDevice>()
                .eq(BasicDevice::getDeviceCode, basicDevice.getDeviceCode())
                .last("limit 1"));
        if (StringUtils.isNotNull(info) && info.getDeviceId().longValue() != deviceId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 导入采集设备
     *
     * @param deviceList 采集设备列表
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importDevice(List<BasicDevice> deviceList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(deviceList) || deviceList.size() == 0)
        {
            throw new ServiceException("导入采集设备数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int row = 2;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BasicDevice basicDevice : deviceList)
        {
            try
            {
                if(StringUtils.isEmpty(basicDevice.getDeviceCode())){
                    continue;
                }
                //获取用户信息
                BasicDevice info = baseMapper.selectOne(new LambdaQueryWrapper<BasicDevice>()
                        .eq(BasicDevice::getDeviceCode, basicDevice.getDeviceCode()).last("limit 1"));
                if (StringUtils.isNull(info))
                {
                    basicDevice.setCreateBy(operName);
                    this.insertBasicDevice(basicDevice);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、采集设备 " + basicDevice.getDeviceCode() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    basicDevice.setDeviceId(info.getDeviceId());
                    basicDevice.setUpdateBy(operName);
                    this.updateBasicDevice(basicDevice);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、采集设备 " + basicDevice.getDeviceCode() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、采集设备 " + basicDevice.getDeviceCode() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、采集设备 " + basicDevice.getDeviceCode() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
            finally {
                row++;
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
